<?php
namespace app\api\controller;

use think\Request;
use app\api\controller\ApiBase;
use app\common\logic\User as UserLogic;

class User extends ApiBase
{
    /**
     * 用户信息设置
     *
     */
    public function modify()
    {
        $data = Request::instance()->param();

        $userLogic = new UserLogic();

        // 校验原始密码是否正确
        $checkPwd = $userLogic->checkPassword($data['uid'], $data['password']);
        
        if (! empty($data['old_password']) && ! empty($data['password']) && ! $checkPwd) {
            return $this->response(1110);
        }

        // 保存头像信息
        if (!empty($data['avatar'])) {
            //匹配出图片的格式 base64格式
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $data['avatar'], $result)){
                $type = $result[2];
                $savePath = ROOT_PATH . 'upload' . DS . 'avatar' . DS;
                if (!file_exists($savePath)) {
                    //检查是否有该文件夹，如果没有就创建，并给予最高权限
                    mkdir($savePath, 0777);
                }
                $saveFile = $savePath . $data['uid'] . '.' . $type;
                $file = file_put_contents($saveFile, base64_decode(str_replace($result[1], '', $data['avatar'])));
                if ($file) {
                    $data['avatar'] = 'upload/avatar/' . $data['uid'] . '.' . $type;
                }
            }
        }

        $result = $userLogic->modify($data);

        if (is_numeric($result)) {
            return $this->response(200);
        } else {
            return $this->response(201, $result);
        }
    }

}
